const overviewService = require('../service/overview.service');
const { getWorkTypeList } = require('../service/workType.service');
const { formatTimestamp } = require('../utils/common');
class OverviewController {
  // 获取订单完成率
  async overviewFinishRate(ctx, next) {
    try {
      const { isMonth } = ctx.query;
      let finishOrderCount = 0, totalOrderCount = 0, finishRate = 0;

      finishOrderCount = isMonth === 'true'
        ? await overviewService.getFinishOrderMonth() // 本月内创建的，且本月完成的订单数
        : await overviewService.getFinishOrderToday(); // 今日创建的，且今日完成的订单数
      totalOrderCount = isMonth === 'true'
        ? await overviewService.getTotalOrderMonth()  // 本月内创建的的订单数
        : await overviewService.getTotalOrderToday(); // 今日创建的的订单数
      finishRate = totalOrderCount !== 0 
          ? parseFloat((finishOrderCount / totalOrderCount).toFixed(2))
          : 0;

      ctx.body = {
        ret: 0,
        data: {
          finish: finishOrderCount,
          total: totalOrderCount,
          rate: finishRate
        }
      };
    } catch (e) {
      console.log('[overview.controller_overviewFinishRate]');
    }
  }

  // 获取新增用户员工数
  async overviewUserWorkerAdd(ctx, next) {
    try {
      const { isMonth } = ctx.query;
      let newUser = 0, newWorker = 0;

      newUser = isMonth === 'true'
        ? await overviewService.getNewUserMonth()
        : await overviewService.getNewUserToday();

      newWorker = isMonth === 'true'
        ? await overviewService.getNewWorkerMonth()
        : await overviewService.getNewWorkerToday();

      ctx.body = {
        ret: 0,
        data: {
          userCount: newUser,
          workerCount: newWorker
        }
      };
    } catch(e) {
      console.log('[overview.controller_overviewUserAdd]', e);
    }
  }

  // 获取订单的好评率或差评率
  async overviewEvaluationRate(ctx, next) {
    try {
      const { isMonth } = ctx.query;
      let goodEva = 0, badEva = 0, orderTotal = 0, goodEvaRate = 0, badEvaRate = 0;

      goodEva = isMonth === 'true'
        ? await overviewService.getGoodEvaMonth()
        : await overviewService.getGoodEvaToday();
      badEva = await overviewService.getBadEva(isMonth);
      orderTotal = isMonth === 'true'
        ? await overviewService.getTotalOrderMonth()
        : await overviewService.getTotalOrderToday();
      
      goodEvaRate = orderTotal === 0
        ? 0
        : parseFloat((goodEva / orderTotal).toFixed(2));
      badEvaRate = orderTotal === 0
        ? 0
        : parseFloat((badEva / orderTotal).toFixed(2));

      ctx.body = {
        ret: 0,
        data: {
          goodRate: goodEvaRate,
          badRate: badEvaRate
        }
      }
      
    } catch(e) {
      console.log('[overview.controller_overviewEvaluationRate]', e);
    }
  }
  
  // 获取订单交易量
  async overviewOrderDealCount(ctx, next) {
    try {
      const { isMonth } = ctx.query;
      const curDate = (new Date).getDate(); // 今天的日期
      let timeArr = [],   // 时间数组
          time = isMonth === 'false' ? 7 : curDate - 1, // 获取多少天
          flag = 24 * 60 * 60 * 1000 - 1; 
      const curDateStartTimestamp = new Date((new Date()).toLocaleDateString()).getTime(); // 获取今日0点的时间戳
      const curDateEndTimestamp = curDateStartTimestamp + flag;
      for (let i = time; i > 1; i --) {
        let start = curDateStartTimestamp - (i * (flag + 1));
        let end = start + flag;
        timeArr.push([formatTimestamp(start), formatTimestamp(end)]);
      }
      timeArr.push([formatTimestamp(curDateStartTimestamp), formatTimestamp(curDateEndTimestamp)]);
      // console.log(timeArr); // 获取到需要拿到的天的数据

      // 获取到工作类型的数据并合并成一个数组
      const workTypeArr = await getWorkTypeList();
      const workType = workTypeArr.map(item => item.work);

      let dataArr = [];

      for (let i = 0; i < timeArr.length; i++) {
        let result = await overviewService.getCountByWorkerType(timeArr[i]);
        let newArray = [];
        result.forEach(singleWork => {
          newArray.push(singleWork['work']);
        })

        // 判断是否包含有数据库中工作类型的数据，若没有则添加
        workType.forEach(singleWorkType => {
          if (!newArray.includes(singleWorkType))
            result.push({ work: singleWorkType, count: 0 });
        })

        // 添加当天的订单总数
        let count = 0;
        result.forEach(item => {
          count += item.count;
        });
        result.push({ work: '全部', count: count });

        dataArr.push({
          time: timeArr[i][0].split(' ')[0],
          data: result
        });
      }

      ctx.body = {
        ret: 0,
        data: dataArr
      }
    } catch (e) {
      console.log('[overview.controller_overviewOrderDealCount]', e);
    }
  }
}

module.exports = new OverviewController();